package com.leetcode.editor.cn.other;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author:
 * @create: 2020-12-01 15:04
 **/
public class LengthOfLongestSubstringTwoDistinct {
    public static void main(String[] args) {
        Solution solution = new LengthOfLongestSubstringTwoDistinct().new Solution();
        int result = solution.lengthOfLongestSubstringTwoDistinct("ccaabbb");
        System.out.println(result);
    }

    class Solution {

        public int lengthOfLongestSubstringTwoDistinct(String s) {
            char[] chars = s.toCharArray();
            int len = chars.length;
            Map<Character, Integer> map = new HashMap<>();//final int[] count = new int[256];
            int left = 0, right = 0;
            int count = 0;//不同的字符数量
            int maxLength=0;
            while (right < len) {
                //在map中获取该字符出现的次数(不存在则为0),次数+1
                int rightNumber = map.getOrDefault(chars[right], 0) + 1;
                map.put(chars[right], rightNumber);//更新map
                if (rightNumber == 1) {//第一次出现
                    count++;
                }
                right++;
                if(count<=2){
                    maxLength=Math.max(maxLength,right-left);
                }
                while (count > 2) {
                    //左侧移除一个字符，在map中获取该字符出现的次数-1
                    int leftNumber = map.get(chars[left]) - 1;
                    map.put(chars[left], leftNumber);//更新map
                    if (leftNumber == 0) {
                        count--;
                    }
                    left++;
                }
            }
            return maxLength;
        }
    }
}
